package com.ce.framework.util.node;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ce.framework.util.APIUtil;


public class APITreeNode {

	String id,text;
	List<APITreeNode> children;
	public APITreeNode(File f){
		id = f.getName();
		text = getTitle(f);
		if(f.listFiles()!=null){
			for(File file:f.listFiles()){
				if(".svn".equals(file.getName())){
					continue;
				}
				if(children==null){
					children = new ArrayList<APITreeNode>();
				}
				children.add(new APITreeNode(file));
			}
		}
	}
	static Pattern pat = Pattern.compile(".*<div id=\"page-title\">\\s*(.+)\\s*</div>.*");
	public String getTitle(File f) {
		if(APIUtil.cataMap.containsKey(f.getName())){
			return APIUtil.cataMap.get(f.getName());
		}
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(f),"UTF-8"));
			String line = null;
			while((line=in.readLine())!=null){
				Matcher mat = pat.matcher(line);
				if(mat.matches()){
					return mat.group(1);
				}
			}
			return f.getName();
		} catch (Exception e) {
			return f.getName();
		}
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public List<APITreeNode> getChildren() {
		return children;
	}
//	public String getChildren() {
//		if(children==null){
//			return null;
//		}
//		else{
//			JSONArray ary = new JSONArray();
//			for(Node n:children){
//				ary.add(n);
//			}
//			return ary.toString();
//		}
//	}
	public void setChildren(List<APITreeNode> children) {
		this.children = children;
	}
}